﻿
using MediatR;
using MyMES.Domain.W.Liststructure;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.W.realize;

namespace MyMES.Read.API.Application.CommendHandlers.W.realize
{
    public class GetSupplierCommandHandlers : IRequestHandler<GetSupplierCommands, APIPaging<List<Supplier>>>
    {
        private readonly IBaseRepository<Supplier> supplierRepository;

        public GetSupplierCommandHandlers(IBaseRepository<Supplier> supplierRepository)
        {
            this.supplierRepository = supplierRepository;
        }

        /// <summary>
        /// 显示供应商信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIPaging<List<Supplier>>> Handle(GetSupplierCommands request, CancellationToken cancellationToken)
        {
            APIPaging<List<Supplier>> result=new APIPaging<List<Supplier>>();
            result.Code = APIEnum.查询成功;
            result.Msg = "查询成功";
            string sql = "select * from Supplier where IsDelete =false ORDER BY SupplierId DESC";
            var list = await supplierRepository.SelectAsync(sql);
            if (!string.IsNullOrEmpty(request.SupplierName))
            {
                list=list.Where(x=>x.SupplierName.Contains(request.SupplierName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.SupplierNumber))
            {
                list = list.Where(x => x.SupplierNumber.Contains(request.SupplierNumber)).ToList();
            }
            if (!string.IsNullOrEmpty(request.SupplierEnglishName))
            {
                list = list.Where(x => x.SupplierEnglishName.Contains(request.SupplierEnglishName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.SupplierAbbreviation))
            {
                list = list.Where(x => x.SupplierAbbreviation.Contains(request.SupplierAbbreviation)).ToList();
            }
            if (request.IsEnable!=null)
            {
                  var ena= request.IsEnable==1 ? true : false;
                list = list.Where(x => x.IsEnable == ena).ToList();
            }
            result.TotalCount = list.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            list = list.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.data = list;
            return result;
        }
    }
}
